package com.wanli.graalvmdemo.configuration.components;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

@Component
public class LoginFailHandler implements ServerAuthenticationFailureHandler {

    @Override
    public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, AuthenticationException exception) {
//        String errorMessage = "无效的凭证";
//        if (exception instanceof BadCredentialsException) {
//            errorMessage = exception.getMessage(); // 获取详细错误，如“密码错误”
//        } else if (exception.getCause() instanceof UsernameNotFoundException) {
//            errorMessage = "用户不存在";
//        }
//
//        logger.info("登录失败：{}", errorMessage);
//
//        // 重定向到登录页面，带上错误信息
//        String redirectUrl = "/auth/login?errorMessage=" + URLEncoder.encode(errorMessage, StandardCharsets.UTF_8);
//        webFilterExchange.getExchange().getResponse().setStatusCode(HttpStatus.FOUND); // 302 重定向
//        webFilterExchange.getExchange().getResponse().getHeaders().setLocation(URI.create(redirectUrl));
//        return webFilterExchange.getExchange().getResponse().setComplete();

        return Mono.defer(() -> Mono.just(webFilterExchange.getExchange().getResponse()).flatMap(response -> {
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            DataBuffer dataBuffer = dataBufferFactory.wrap("登录失败".getBytes());
            return response.writeWith(Mono.just(dataBuffer));
        }));
    }
}